package com.lmc.forum.controller;

import com.lmc.forum.common.AppResult;
import com.lmc.forum.common.ResultCode;
import com.lmc.forum.config.AppConfig;
import com.lmc.forum.model.User;
import com.lmc.forum.services.IUserService;
import com.lmc.forum.utils.CryptoUtil;
import com.lmc.forum.utils.StringUtil;
import com.lmc.forum.utils.UUIDUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "用户接口", description = "用户的增删查改")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public AppResult register(
            @Parameter(description = "用户名", required = true, example = "boy")
            @NotBlank @RequestParam(value = "username") String username,
            @Parameter(description = "昵称", required = true, example = "boy")
            @NotBlank @RequestParam(value = "nickname") String nickname,
            @Parameter(description = "密码", required = true, example = "123456")
            @NotBlank @RequestParam(value = "password") String password,
            @Parameter(description = "重复密码", required = true, example = "123456")
            @NotBlank @RequestParam(value = "passwordRepeat") String passwordRepeat) {
        if (!password.equals(passwordRepeat)) {
// 记录⽇志
            log.info(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
// 返回错误信息
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 1.基本信息赋值
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        // 2.2 加密密码
        String salt = UUIDUtil.UUID_32();
        String encryptPassword = CryptoUtil.md5Salt(password, salt);
// 2.3 设置密码
        user.setPassword(encryptPassword);
        user.setSalt(salt);
// 3. 调⽤Service
        userService.createNormalUser(user);
// 4. 返回
        return AppResult.success();
    }

    /**
     * @param request  请求，用来获取session
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @Parameter(description = "用户名", required = true, example = "boy")
                           @NotBlank @RequestParam(value = "username") String username,
                           @Parameter(description = "密码", required = true, example = "123456")
                           @NotBlank @RequestParam(value = "password") String password) {

        User user = userService.login(username, password);
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION, user);
        log.info("用户登录成功");
        return AppResult.success();
    }


    /**
     * 获取用户信息
     *
     * @param request 请求，用来获取当前登录用户session
     * @param id      用户ID
     * @return
     */
    @Operation(summary = "获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @Parameter(description = "用户ID", required = false, example = "1")
                                       @RequestParam(value = "id", required = false) Long id) {
        User user = null;
        if (id == null) {
            HttpSession session = request.getSession(false);
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
//            用户未登录
            if (session == null || session.getAttribute(AppConfig.USER_SESSION) == null) {
                log.warn("用户未登录");
                return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
            }
        } else {
            user = userService.selectUserById(id);
            if (user == null) {
                log.warn("用户不存在");
                return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
            }
        }
        return AppResult.success(user);

    }

    @Operation(summary = "用户登出")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            log.info("用户退出登录");
            session.invalidate();
        }
        return AppResult.success("用户退出登录");
    }


        /**
         * 修改个⼈信息
         * @param username ⽤⼾名
         * @param nickname 昵称
         * @param gender 性别
         * @param email 邮箱
         * @param phoneNum 电话号
         * @param remark 个⼈简介
         * @return AppResult
         */
    @Operation(summary = "修改用户信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                     @Parameter(description = "用户名", required = true, example = "boy")
                     @RequestParam(value = "username" , required = false) String username,
                     @Parameter(description = "昵称", required = true, example = "boy")
                     @RequestParam(value = "nickname" , required = false) String nickname,
                     @Parameter(description = "性别", required = true, example = "1")
                     @RequestParam(value = "gender" , required = false) Byte gender,
                     @Parameter(description = "邮箱", required = true, example = "123456@qq.com")
                     @RequestParam(value = "email" , required = false) String email,
                     @Parameter(description = "电话号码", required = true, example = "12345678901")
                     @RequestParam(value = "phoneNum" , required = false) String phoneNum,
                     @Parameter(description = "简介", required = true, example = "I am a boy")
                     @RequestParam(value = "remark" , required = false) String remark) {
        // 1. 接收参数
// 2. 对参数做⾮空校验（全部都为空，则返回错误描述）
        if (StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(email) && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark) && gender == null) {
// 返回错误信息
            return AppResult.failed("请输⼊要修改的内容");
        }
// 从session中获取⽤⼾Id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
// 3. 封装对象
        User updateUser = new User();
        updateUser.setId(user.getId()); // ⽤⼾Id
        updateUser.setUsername(username); // ⽤⼾名
        updateUser.setNickname(nickname); // 昵称
        updateUser.setGender(gender); // 性别
        updateUser.setEmail(email); // 邮箱
        updateUser.setPhoneNum(phoneNum); // 电话
        updateUser.setRemark(remark); // 个⼈简介
// 4. 调⽤Service中的⽅法
        userService.modifyInfo(updateUser);
// 5. 查询最新的⽤⼾信息
        user = userService.selectById(user.getId());
// 6. 把最新的⽤⼾信息设置到session中
        session.setAttribute(AppConfig.USER_SESSION, user);
// 7. 返回结果
        return AppResult.success(user);
    }

    @Operation(summary = "修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPwd(HttpServletRequest request,
                               @Parameter(description = "新密码", required = true, example = "123456")
                               @NotBlank @RequestParam(value = "newPassword") String newPassword,
                               @Parameter(description = "旧密码", required = true, example = "123456")
                               @NotBlank @RequestParam(value = "oldPassword") String oldPassword,
                               @Parameter(description = "确认密码", required = true, example = "123456")
                               @NotNull  @RequestParam(value = "passwordRepeat")  String passwordRepeat) {
        // 1. 校验新密码与确认密码是否相同
        if (!newPassword.equals(passwordRepeat)) {
// 返回错误描述
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
// 2. 获取当前登录的⽤⼾信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
// 3. 调⽤Service
        userService.modifyPassword(user.getId(), newPassword, oldPassword);
// 4. 销毁session
        if (session != null) {
            session.invalidate();
        }
// 5. 返回结果
        return AppResult.success();
    }
}
